package com.literature.search.file.service.impl;

import com.literature.search.core.common.FileStateConstant;
import com.literature.search.core.common.MessageConstant;
import com.literature.search.core.entity.FileDocument;
import com.literature.search.core.entity.FileReview;
import com.literature.search.core.entity.R.AjaxJson;
import com.literature.search.file.service.IFileReviewService;
import com.literature.search.file.service.IFileService;
import com.literature.search.file.service.ITaskExecuteService;
import com.mongodb.DuplicateKeyException;
import org.apache.commons.compress.utils.Lists;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author: DangKong
 * @Date: 2023/3/3 14:17
 * @Description:
 */
@Service
public class FileReviewServiceImpl implements IFileReviewService {

    public static final String FILE_REVIEW_COLLECTION = "file_review";

    @Resource
    MongoTemplate mongoTemplate;

    @Resource
    private IFileService fileService;

    @Resource
    private ITaskExecuteService taskExecuteService;

    @Resource
    private UploadRecordServiceImpl uploadRecordService; // 上传记录


    @Override
    public AjaxJson rejectBatch(List<String> ids) {
        if (fileIdExist(ids)) {
            return AjaxJson.get(MessageConstant.PROCESS_ERROR_CODE, MessageConstant.OPERATE_FAILED);
        }
        List<FileDocument> fileDocumentList = fileService.queryAndUpdate(ids.toArray(new String[0])); // 查询并更新文档的状态
        if (CollectionUtils.isEmpty(fileDocumentList)) {
            return AjaxJson.get(MessageConstant.PROCESS_ERROR_CODE, MessageConstant.OPERATE_FAILED);
        }
        List<FileReview> fileReviews = Lists.newArrayList(); // 保存文档评审的集合
        for (FileDocument fileDocument : fileDocumentList) {
            fileReviews.add(fileReviewInstance(fileDocument, null, false));
            // 更新上传记录
            uploadRecordService.updateStatus(fileDocument.getUserId(), fileDocument.getId(), FileStateConstant.FILE_UPLOAD_STATUS_CHECKED_FAIL);
        }

        try {
            mongoTemplate.insert(fileReviews, FILE_REVIEW_COLLECTION);
            // 操作成功，文档正在索引
            return AjaxJson.getSuccess(MessageConstant.OPERATE_SUCCESS);
        } catch (DuplicateKeyException e) {
            return AjaxJson.get(MessageConstant.PROCESS_ERROR_CODE,MessageConstant.OPERATE_FAILED);
        }
    }


    @Override
    public AjaxJson approveBatch(List<String> fileIds) {
        if (fileIdExist(fileIds)) {
            return AjaxJson.get(MessageConstant.PROCESS_ERROR_CODE, MessageConstant.OPERATE_FAILED);
        }
        List<FileDocument> fileDocumentList = fileService.queryAndUpdate(fileIds.toArray(new String[0])); // 查询并更新文档的状态
        if (CollectionUtils.isEmpty(fileDocumentList)) {
            return AjaxJson.get(MessageConstant.PROCESS_ERROR_CODE, MessageConstant.OPERATE_FAILED);
        }
        List<FileReview> fileReviews = Lists.newArrayList(); // 保存文档评审的集合
        for (FileDocument fileDocument : fileDocumentList) {
            taskExecuteService.execute(fileDocument); // 执行文档的任务
            fileReviews.add(fileReviewInstance(fileDocument, null, true));
            // 更新上传记录
            uploadRecordService.updateStatus(fileDocument.getUserId(), fileDocument.getId(), FileStateConstant.FILE_UPLOAD_STATUS_CHECKED);
        }
        // 可以进行批量操作，相对效率较save更高
        try {
            mongoTemplate.insert(fileReviews, FILE_REVIEW_COLLECTION);
            // 操作成功，文档正在索引
            return AjaxJson.getSuccess(MessageConstant.OPERATE_SUCCESS);
        } catch (DuplicateKeyException e) {
            return AjaxJson.get(MessageConstant.PROCESS_ERROR_CODE,MessageConstant.OPERATE_FAILED);
        }
    }

    /**
     * @Description 创建一条文档评审的实例
     * @Date 10:24 2022/12/10
     * @Param [fileDocument, reason, approve]
     **/
    private FileReview fileReviewInstance(FileDocument fileDocument, String reason, boolean approve) {
        if (!StringUtils.hasText(fileDocument.getId())) {
            return null;
        }
        FileReview fileReview = new FileReview();
        fileReview.setFileId(fileDocument.getId());
        fileReview.setFileName(fileDocument.getFileName());
        fileReview.setUserId(fileDocument.getUserId());
        fileReview.setUserName(fileDocument.getUserName());
        fileReview.setCheckState(approve);
        fileReview.setReadState(false);
        fileReview.setUserRemove(false);
        fileReview.setReviewLog(reason);
        fileReview.setCreateDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        fileReview.setUpdateDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return fileReview;
    }

    /**
     * @Description 判断这个文档是否已经存在于评审列表中
     * @Param [docIds]
     * @return boolean
     **/
    private boolean fileIdExist(List<String> fileIds) {
        Query query = new Query(Criteria.where("file_id").in(fileIds));
        return mongoTemplate.count(query, FileReview.class, FILE_REVIEW_COLLECTION) > 0;
    }
}
